package thoven.achievement.net.ideapluginachievement.service

import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.fileChooser.FileSaverDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VirtualFileWrapper
import com.intellij.ui.JBColor
import com.intellij.util.ui.UIUtil
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import thoven.achievement.net.ideapluginachievement.model.Achievement
import thoven.achievement.net.ideapluginachievement.model.AchievementType
import thoven.achievement.net.ideapluginachievement.model.AggregatedCodeStats
import thoven.achievement.net.ideapluginachievement.model.CodeStats
import java.awt.*
import java.awt.image.BufferedImage
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
import javax.imageio.ImageIO
import javax.swing.JComponent

/**
 * 数据导出与分享服务
 */
@Service(Service.Level.PROJECT)
class ExportService(private val project: Project) {
    
    companion object {
        fun getInstance(project: Project): ExportService = project.getService(ExportService::class.java)
        private val LOG = logger<ExportService>()
    }
    
    private val codeStatsService by lazy { CodeStatsService.getInstance(project) }
    private val settingsService by lazy { SettingsService.getInstance() }
    
    /**
     * 导出格式枚举
     */
    enum class ExportFormat(val displayName: String, val extension: String, val description: String) {
        JSON("JSON格式", "json", "结构化数据，便于程序处理"),
        CSV("CSV格式", "csv", "表格数据，可用Excel打开"),
        MARKDOWN("Markdown格式", "md", "文档格式，便于阅读和分享")
    }
    
    /**
     * 分享卡片类型
     */
    enum class ShareCardType(val displayName: String, val width: Int, val height: Int) {
        ACHIEVEMENT("成就分享", 800, 400),
        DAILY_SUMMARY("日度总结", 600, 800),
        ANNUAL_REPORT("年度报告", 1000, 1400)
    }
    
    /**
     * 导出数据到文件
     */
    fun exportData(format: ExportFormat): Boolean {
        try {
            val descriptor = FileSaverDescriptor(
                "导出编码数据",
                "选择导出位置",
                format.extension
            )
            
            val chooser = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, project)
            val defaultName = "code-achievement-${LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))}"
            
            val fileWrapper: VirtualFileWrapper? = chooser.save(defaultName)
            
            if (fileWrapper != null) {
                val file = fileWrapper.getFile()
                when (format) {
                    ExportFormat.JSON -> exportToJson(file)
                    ExportFormat.CSV -> exportToCsv(file)
                    ExportFormat.MARKDOWN -> exportToMarkdown(file)
                }
                
                Messages.showInfoMessage(
                    project,
                    "数据已成功导出到：\n${file.absolutePath}",
                    "导出成功"
                )
                return true
            }
        } catch (e: Exception) {
            LOG.error("导出数据失败", e)
            Messages.showErrorDialog(
                project,
                "导出失败：${e.message}",
                "导出错误"
            )
        }
        return false
    }
    
    /**
     * 导出为JSON格式
     */
    private fun exportToJson(file: File) {
        val stats = codeStatsService.getTodayStats()
        val aggregated = codeStatsService.getAggregatedStats()
        val unlockedAchievements = codeStatsService.getUnlockedAchievements()
        val state = codeStatsService.getState()
        
        val gson = GsonBuilder().setPrettyPrinting().create()
        val exportData = JsonObject().apply {
            addProperty("exportDate", LocalDate.now().toString())
            addProperty("projectName", project.name)
            
            // 基础统计
            add("aggregatedStats", gson.toJsonTree(aggregated))
            add("dailyStats", gson.toJsonTree(stats))
            
            // 成就数据
            add("unlockedAchievements", gson.toJsonTree(unlockedAchievements.map { 
                mapOf(
                    "type" to it.type.name,
                    "name" to it.getName(),
                    "description" to it.getDescription(),
                    "unlockDate" to if (it.unlockTimestamp > 0) Date(it.unlockTimestamp).toString() else null
                )
            }))
            
            // 扩展统计
            add("extendedStats", gson.toJsonTree(mapOf(
                "consecutiveDays" to state.consecutiveDays,
                "totalProjects" to 1,
                "favoriteLanguages" to stats.groupBy { it.language }
                    .mapValues { entry -> entry.value.sumOf { stat -> stat.addedLines } }
                    .entries.sortedByDescending { it.value }
                    .take(5)
                    .associate { it.key to it.value }
            )))
        }
        
        FileWriter(file).use { writer ->
            gson.toJson(exportData, writer)
        }
    }
    
    /**
     * 导出为CSV格式
     */
    private fun exportToCsv(file: File) {
        val stats = codeStatsService.getTodayStats()
        val aggregated = codeStatsService.getAggregatedStats()
        val unlockedAchievements = codeStatsService.getUnlockedAchievements()
        
        FileWriter(file).use { writer ->
            // 导出汇总数据
            writer.append("=== 汇总统计 ===\n")
            writer.append("指标,数值\n")
            writer.append("今日新增行数,${aggregated.todayAdded}\n")
            writer.append("今日删除行数,${aggregated.todayDeleted}\n")
            writer.append("累计新增行数,${aggregated.totalAdded}\n")
            writer.append("累计删除行数,${aggregated.totalDeleted}\n")
            writer.append("累计净增行数,${aggregated.totalNet}\n")
            writer.append("连续编程天数,${codeStatsService.getConsecutiveDays()}\n")
            writer.append("已解锁成就数,${unlockedAchievements.size}\n")
            
            writer.append("\n=== 每日详细数据 ===\n")
            writer.append("日期,语言,新增行数,删除行数,净增行数\n")
            
            stats.forEach { stat ->
                writer.append("${stat.date},${stat.language},${stat.addedLines},${stat.deletedLines},${stat.netLines}\n")
            }
            
            writer.append("\n=== 已解锁成就 ===\n")
            writer.append("成就名称,描述,解锁时间\n")
            
            unlockedAchievements.forEach { achievement ->
                val unlockDate = if (achievement.unlockTimestamp > 0) {
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(achievement.unlockTimestamp))
                } else {
                    "未知"
                }
                writer.append("${achievement.getName()},\"${achievement.getDescription()}\",${unlockDate}\n")
            }
        }
    }
    
    /**
     * 导出为Markdown格式
     */
    private fun exportToMarkdown(file: File) {
        val stats = codeStatsService.getTodayStats()
        val aggregated = codeStatsService.getAggregatedStats()
        val unlockedAchievements = codeStatsService.getUnlockedAchievements()
        val consecutiveDays = codeStatsService.getConsecutiveDays()
        
        FileWriter(file).use { writer ->
            writer.append("# 📊 编码成就报告\n\n")
            writer.append("**项目**: ${project.name}  \n")
            writer.append("**导出时间**: ${LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"))}  \n")
            writer.append("**连续编程**: $consecutiveDays 天  \n\n")
            
            // 汇总统计
            writer.append("## 📈 统计概览\n\n")
            writer.append("| 指标 | 数值 |\n")
            writer.append("|------|------|\n")
            writer.append("| 🔥 今日新增 | ${aggregated.todayAdded} 行 |\n")
            writer.append("| 🗑️ 今日删除 | ${aggregated.todayDeleted} 行 |\n")
            writer.append("| 📊 今日净增 | ${aggregated.todayAdded - aggregated.todayDeleted} 行 |\n")
            writer.append("| 💪 累计新增 | ${aggregated.totalAdded} 行 |\n")
            writer.append("| 🔄 累计删除 | ${aggregated.totalDeleted} 行 |\n")
            writer.append("| 🎯 累计净增 | ${aggregated.totalNet} 行 |\n")
            writer.append("| 🏆 解锁成就 | ${unlockedAchievements.size} 个 |\n\n")
            
            // 语言分布
            val languageStats = stats.groupBy { it.language }
                .mapValues { entry -> entry.value.sumOf { stat -> stat.addedLines } }
                .entries.sortedByDescending { it.value }
            
            if (languageStats.isNotEmpty()) {
                writer.append("## 💻 编程语言分布\n\n")
                writer.append("| 语言 | 代码行数 | 占比 |\n")
                writer.append("|------|----------|------|\n")
                
                val totalLines = languageStats.sumOf { it.value }
                languageStats.forEach { (language, lines) ->
                    val percentage = if (totalLines > 0) (lines * 100.0 / totalLines) else 0.0
                    writer.append("| $language | $lines | ${String.format("%.1f", percentage)}% |\n")
                }
                writer.append("\n")
            }
            
            // 成就墙
            if (unlockedAchievements.isNotEmpty()) {
                writer.append("## 🏆 成就墙\n\n")
                unlockedAchievements.forEach { achievement ->
                    writer.append("### ${achievement.getIcon()} ${achievement.getName()}\n")
                    writer.append("${achievement.getDescription()}\n\n")
                }
            }
            
            // 近期编程记录
            if (stats.isNotEmpty()) {
                writer.append("## 📅 近期编程记录\n\n")
                writer.append("| 日期 | 语言 | 新增 | 删除 | 净增 |\n")
                writer.append("|------|------|------|------|------|\n")
                
                stats.sortedByDescending { it.date }.take(10).forEach { stat ->
                    writer.append("| ${stat.date} | ${stat.language} | +${stat.addedLines} | -${stat.deletedLines} | ${stat.netLines} |\n")
                }
            }
            
            writer.append("\n---\n")
            writer.append("*由 Code Achievement 插件生成*\n")
        }
    }
    
    /**
     * 生成分享卡片图片
     */
    fun generateShareCard(type: ShareCardType, data: Map<String, Any>? = null): Boolean {
        try {
            val descriptor = FileSaverDescriptor(
                "保存分享卡片",
                "选择保存位置",
                "png"
            )
            
            val chooser = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, project)
            val defaultName = when (type) {
                ShareCardType.ACHIEVEMENT -> "achievement-card-${System.currentTimeMillis()}"
                ShareCardType.DAILY_SUMMARY -> "daily-summary-${LocalDate.now()}"
                ShareCardType.ANNUAL_REPORT -> "annual-report-${LocalDate.now().year}"
            }
            
            val fileWrapper: VirtualFileWrapper? = chooser.save(defaultName)
            
            if (fileWrapper != null) {
                val file = fileWrapper.getFile()
                val image = when (type) {
                    ShareCardType.ACHIEVEMENT -> createAchievementCard(data)
                    ShareCardType.DAILY_SUMMARY -> createDailySummaryCard()
                    ShareCardType.ANNUAL_REPORT -> createAnnualReportCard()
                }
                
                ImageIO.write(image, "png", file)
                
                Messages.showInfoMessage(
                    project,
                    "分享卡片已保存到：\n${file.absolutePath}",
                    "保存成功"
                )
                return true
            }
        } catch (e: Exception) {
            LOG.error("生成分享卡片失败", e)
            Messages.showErrorDialog(
                project,
                "生成失败：${e.message}",
                "生成错误"
            )
        }
        return false
    }
    
    /**
     * 创建成就分享卡片
     */
    private fun createAchievementCard(data: Map<String, Any>?): BufferedImage {
        val width = ShareCardType.ACHIEVEMENT.width
        val height = ShareCardType.ACHIEVEMENT.height
        
        val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
        val g2d = image.createGraphics()
        
        // 启用抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
        
        // 渐变背景
        val themeColor = settingsService.getThemeColor()
        val gradient = GradientPaint(
            0f, 0f, Color.decode(themeColor.primaryColor),
            width.toFloat(), height.toFloat(), Color.decode(themeColor.accentColor)
        )
        g2d.paint = gradient
        g2d.fillRect(0, 0, width, height)
        
        // 半透明覆盖层
        g2d.color = Color(0, 0, 0, 50)
        g2d.fillRect(0, 0, width, height)
        
        // 获取成就数据
        val achievement = data?.get("achievement") as? Achievement
        val unlockedCount = data?.get("unlockedCount") as? Int ?: codeStatsService.getUnlockedAchievements().size
        val totalCount = AchievementType.values().size
        
        // 白色文字
        g2d.color = Color.WHITE
        
        // 标题
        g2d.font = Font("微软雅黑", Font.BOLD, 48)
        val title = "🏆 Code Achievement"
        val titleMetrics = g2d.fontMetrics
        val titleX = (width - titleMetrics.stringWidth(title)) / 2
        g2d.drawString(title, titleX, 80)
        
        if (achievement != null) {
            // 单个成就展示
            g2d.font = Font("微软雅黑", Font.BOLD, 72)
            val icon = achievement.getIcon()
            val iconMetrics = g2d.fontMetrics
            val iconX = (width - iconMetrics.stringWidth(icon)) / 2
            g2d.drawString(icon, iconX, 180)
            
            g2d.font = Font("微软雅黑", Font.BOLD, 36)
            val name = achievement.getName()
            val nameMetrics = g2d.fontMetrics
            val nameX = (width - nameMetrics.stringWidth(name)) / 2
            g2d.drawString(name, nameX, 240)
            
            g2d.font = Font("微软雅黑", Font.PLAIN, 24)
            val description = achievement.getDescription()
            val descMetrics = g2d.fontMetrics
            val descX = (width - descMetrics.stringWidth(description)) / 2
            g2d.drawString(description, descX, 280)
        } else {
            // 成就总览
            g2d.font = Font("微软雅黑", Font.BOLD, 64)
            val progressText = "$unlockedCount / $totalCount"
            val progressMetrics = g2d.fontMetrics
            val progressX = (width - progressMetrics.stringWidth(progressText)) / 2
            g2d.drawString(progressText, progressX, 200)
            
            g2d.font = Font("微软雅黑", Font.PLAIN, 28)
            val subtitle = "已解锁成就"
            val subtitleMetrics = g2d.fontMetrics
            val subtitleX = (width - subtitleMetrics.stringWidth(subtitle)) / 2
            g2d.drawString(subtitle, subtitleX, 240)
        }
        
        // 底部信息
        g2d.font = Font("微软雅黑", Font.PLAIN, 20)
        val date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"))
        val dateText = "Generated on $date"
        val dateMetrics = g2d.fontMetrics
        val dateX = (width - dateMetrics.stringWidth(dateText)) / 2
        g2d.drawString(dateText, dateX, height - 40)
        
        g2d.dispose()
        return image
    }
    
    /**
     * 创建日度总结卡片
     */
    private fun createDailySummaryCard(): BufferedImage {
        val width = ShareCardType.DAILY_SUMMARY.width
        val height = ShareCardType.DAILY_SUMMARY.height
        val aggregated = codeStatsService.getAggregatedStats()
        
        val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
        val g2d = image.createGraphics()
        
        // 启用抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
        
        // 白色背景
        g2d.color = Color.WHITE
        g2d.fillRect(0, 0, width, height)
        
        // 顶部彩色条
        val themeColor = settingsService.getThemeColor()
        g2d.color = Color.decode(themeColor.primaryColor)
        g2d.fillRect(0, 0, width, 80)
        
        // 标题
        g2d.color = Color.WHITE
        g2d.font = Font("微软雅黑", Font.BOLD, 36)
        val title = "📊 今日编程总结"
        val titleMetrics = g2d.fontMetrics
        val titleX = (width - titleMetrics.stringWidth(title)) / 2
        g2d.drawString(title, titleX, 50)
        
        // 日期
        g2d.font = Font("微软雅黑", Font.PLAIN, 20)
        val date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"))
        val dateMetrics = g2d.fontMetrics
        val dateX = (width - dateMetrics.stringWidth(date)) / 2
        g2d.drawString(date, dateX, 75)
        
        // 统计数据
        g2d.color = Color.BLACK
        val stats = listOf(
            "📝 新增代码" to "${aggregated.todayAdded} 行",
            "🗑️ 删除代码" to "${aggregated.todayDeleted} 行",
            "📊 净增代码" to "${aggregated.todayAdded - aggregated.todayDeleted} 行",
            "🏆 已解锁成就" to "${codeStatsService.getUnlockedAchievements().size} 个",
            "⭐ 连续编程" to "${codeStatsService.getState().consecutiveDays} 天"
        )
        
        var y = 150
        stats.forEach { (label, value) ->
            g2d.font = Font("微软雅黑", Font.BOLD, 28)
            g2d.drawString(label, 50, y)
            
            g2d.font = Font("微软雅黑", Font.PLAIN, 32)
            g2d.color = Color.decode(themeColor.primaryColor)
            val valueMetrics = g2d.fontMetrics
            g2d.drawString(value, width - valueMetrics.stringWidth(value) - 50, y)
            
            g2d.color = Color.BLACK
            y += 80
        }
        
        // 底部签名
        g2d.font = Font("微软雅黑", Font.PLAIN, 18)
        g2d.color = Color.GRAY
        val signature = "Generated by Code Achievement Plugin"
        val sigMetrics = g2d.fontMetrics
        val sigX = (width - sigMetrics.stringWidth(signature)) / 2
        g2d.drawString(signature, sigX, height - 30)
        
        g2d.dispose()
        return image
    }
    
    /**
     * 创建年度报告卡片
     */
    private fun createAnnualReportCard(): BufferedImage {
        val width = ShareCardType.ANNUAL_REPORT.width
        val height = ShareCardType.ANNUAL_REPORT.height
        val aggregated = codeStatsService.getAggregatedStats()
        val year = LocalDate.now().year
        
        val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
        val g2d = image.createGraphics()
        
        // 启用抗锯齿和高质量渲染
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
        
        // 多层渐变背景
        val themeColor = settingsService.getThemeColor()
        val primaryColor = Color.decode(themeColor.primaryColor)
        val accentColor = Color.decode(themeColor.accentColor)
        
        // 主渐变背景
        val mainGradient = GradientPaint(
            0f, 0f, primaryColor,
            0f, height.toFloat(), accentColor
        )
        g2d.paint = mainGradient
        g2d.fillRect(0, 0, width, height)
        
        // 装饰圆圈
        g2d.color = Color(255, 255, 255, 20)
        g2d.fillOval(-100, -100, 300, 300)
        g2d.fillOval(width - 200, height - 200, 300, 300)
        g2d.color = Color(255, 255, 255, 10)
        g2d.fillOval(width - 150, 50, 200, 200)
        
        // 顶部装饰条
        g2d.color = Color(255, 255, 255, 40)
        g2d.fillRoundRect(50, 50, width - 100, 8, 4, 4)
        
        // 标题区域
        g2d.color = Color.WHITE
        g2d.font = Font("微软雅黑", Font.BOLD, 72)
        val title = "$year 年度总结"
        val titleMetrics = g2d.fontMetrics
        val titleX = (width - titleMetrics.stringWidth(title)) / 2
        g2d.drawString(title, titleX, 140)
        
        // 副标题
        g2d.font = Font("微软雅黑", Font.PLAIN, 24)
        g2d.color = Color(255, 255, 255, 200)
        val subtitle = "Code Achievement 年度编程报告"
        val subtitleMetrics = g2d.fontMetrics
        val subtitleX = (width - subtitleMetrics.stringWidth(subtitle)) / 2
        g2d.drawString(subtitle, subtitleX, 175)
        
        // 主要统计数据 - 使用卡片式设计  
        data class StatCard(val icon: String, val label: String, val value: String, val color: Color)
        val mainStats = listOf(
            StatCard("💻", "总代码行数", "${aggregated.totalAdded}", Color(52, 152, 219)),
            StatCard("🏆", "解锁成就", "${codeStatsService.getUnlockedAchievements().size}", Color(241, 196, 15)),
            StatCard("📅", "编程天数", "${codeStatsService.getState().consecutiveDays}", Color(155, 89, 182))
        )
        
        var y = 260
        mainStats.forEach { stat ->
            // 卡片阴影
            g2d.color = Color(0, 0, 0, 30)
            g2d.fillRoundRect(70, y - 45, width - 140, 90, 20, 20)
            
            // 卡片背景
            g2d.color = Color(255, 255, 255, 90)
            g2d.fillRoundRect(65, y - 50, width - 130, 90, 20, 20)
            
            // 左侧彩色条
            g2d.color = stat.color
            g2d.fillRoundRect(65, y - 50, 8, 90, 4, 4)
            
            // 图标
            g2d.color = stat.color
            g2d.font = Font("Apple Color Emoji", Font.PLAIN, 36)
            g2d.drawString(stat.icon, 100, y - 10)
            
            // 标签
            g2d.color = Color(60, 60, 60)
            g2d.font = Font("微软雅黑", Font.BOLD, 28)
            g2d.drawString(stat.label, 150, y - 10)
            
            // 数值
            g2d.color = stat.color
            g2d.font = Font("微软雅黑", Font.BOLD, 42)
            val valueMetrics = g2d.fontMetrics
            g2d.drawString(stat.value, width - valueMetrics.stringWidth(stat.value) - 100, y - 5)
            
            y += 110
        }
        
        // 成就展示区域
        val achievements = codeStatsService.getUnlockedAchievements().take(8)
        if (achievements.isNotEmpty()) {
            y += 60
            
            // 成就区域背景
            g2d.color = Color(255, 255, 255, 15)
            g2d.fillRoundRect(50, y - 30, width - 100, 250, 25, 25)
            
            // 成就标题
            g2d.color = Color.WHITE
            g2d.font = Font("微软雅黑", Font.BOLD, 32)
            val achieveTitle = "🏆 精选成就"
            val achieveTitleX = (width - g2d.fontMetrics.stringWidth(achieveTitle)) / 2
            g2d.drawString(achieveTitle, achieveTitleX, y)
            
            y += 50
            val iconSize = 70
            val cols = 4
            val rows = 2
            val spacing = 20
            val totalWidth = cols * iconSize + (cols - 1) * spacing
            val startX = (width - totalWidth) / 2
            
            achievements.take(8).forEachIndexed { index, achievement ->
                val row = index / cols
                val col = index % cols
                val x = startX + col * (iconSize + spacing)
                val iconY = y + row * (iconSize + spacing + 10)
                
                // 成就卡片阴影
                g2d.color = Color(0, 0, 0, 40)
                g2d.fillRoundRect(x - 2, iconY - 2, iconSize + 4, iconSize + 4, 18, 18)
                
                // 成就卡片背景
                g2d.color = Color(255, 255, 255, 80)
                g2d.fillRoundRect(x, iconY, iconSize, iconSize, 15, 15)
                
                // 成就图标
                g2d.color = Color(60, 60, 60)
                g2d.font = Font("Apple Color Emoji", Font.PLAIN, 36)
                val icon = achievement.getIcon()
                val iconMetrics = g2d.fontMetrics
                val iconX = x + (iconSize - iconMetrics.stringWidth(icon)) / 2
                g2d.drawString(icon, iconX, iconY + iconSize / 2 + 12)
            }
        }
        
        // 底部装饰和签名
        y = height - 120
        g2d.color = Color(255, 255, 255, 30)
        g2d.fillRoundRect(50, y, width - 100, 2, 1, 1)
        
        // 生成信息
        g2d.font = Font("微软雅黑", Font.PLAIN, 20)
        g2d.color = Color(255, 255, 255, 180)
        val currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"))
        val footerText = "Generated on $currentDate by Code Achievement Plugin"
        val footerMetrics = g2d.fontMetrics
        val footerX = (width - footerMetrics.stringWidth(footerText)) / 2
        g2d.drawString(footerText, footerX, height - 60)
        
        // 版权信息
        g2d.font = Font("微软雅黑", Font.PLAIN, 16)
        g2d.color = Color(255, 255, 255, 120)
        val copyright = "✨ 让编程更有成就感"
        val copyrightMetrics = g2d.fontMetrics
        val copyrightX = (width - copyrightMetrics.stringWidth(copyright)) / 2
        g2d.drawString(copyright, copyrightX, height - 30)
        
        g2d.dispose()
        return image
    }
}
